package com.lzlearn.springboothibernate.dao.impl;

import com.lzlearn.springboothibernate.dao.MyHibernateSqlDao;
import com.lzlearn.springboothibernate.model.User;
import org.springframework.stereotype.Repository;
import org.springframework.transaction.annotation.Transactional;

import javax.annotation.Resource;
import javax.persistence.EntityManager;
import javax.persistence.Parameter;
import javax.persistence.Query;
import java.util.List;

@Repository
public class MyHibernateSqlDaoImpl implements MyHibernateSqlDao {
    @Resource
    private EntityManager entityManager;

    @Override
    public List<User> selectCondition(String name,Integer pageIndex ,Integer pageCount) {
        Query query = entityManager.createNativeQuery("select * from user where name like ?",User.class);
        query.setParameter(1,"%"+name+"%");
        query.setFirstResult((pageIndex-1)*pageCount+1);
        query.setMaxResults(pageCount);
        List resultList = query.getResultList();
        return resultList;
    }
    @Transactional
    @Override
    public boolean updateUser(User user) {
        Query query = entityManager.createNativeQuery("update user set name = :name,age = :age,email = :email where id = :id");
        query
                .setParameter("name",user.getName())
                .setParameter("age",user.getAge())
                .setParameter("email",user.getEmail())
                .setParameter("id",user.getId());
        int i = query.executeUpdate();
        if(i<=0){
            return false;
        }
        return true;
    }
}
